package common;

import gui.GuiManager;

import java.io.File;
import java.sql.Connection;
import java.sql.Statement;

import common.utils.CommonUtils;

import db.freebase.FreeBaseDBImporter;
import db.local.DBLocal;
import db.manager.DBManager;

public class Install {

    public static void main(String[] args) throws Exception {
    	
    	boolean proceed = GuiManager.showInstallProceedDialog();
    	if (!proceed) {
    		return;
    	}
    	System.out.println("Starting install");
    	
    	System.out.println("Starting database");
        DBManager.getInstance().init();
    	String sql;
        Connection connection = DBManager.getInstance().poolConnection();
        Statement statement = connection.createStatement();
        
        System.out.println("Creating tables");
        DBLocal.getInstance().createTables(true);
     
        System.out.println("Downloading latest datadump from freebase server");
        File freeBaseRoot = CommonUtils.downloadAndExtractLatestDatadump(".");
        
        System.out.println("Filling database with characters");
        sql = "CREATE UNIQUE INDEX midIndex ON FictionalCharacter(freeBaseMID)";
        statement.executeUpdate(sql);
        FreeBaseDBImporter.importToDB(freeBaseRoot);
        CommonUtils.deleteDirectory(freeBaseRoot);
        sql = "DROP INDEX midIndex ON FictionalCharacter";
        statement.executeUpdate(sql);
        
        System.out.println("Filling database with application data");
        DBLocal.getInstance().propertiesTableInitialPopulation();

        System.out.println("Closing database");
        DBManager.getInstance().returnConnection(connection);
        DBManager.getInstance().close();
        
        System.out.println("Finished install");
    }
}
